//
//  UICollectionView+Reusable.swift
//  
//
//  Created by tangbl93 on 2021/2/5.
//

import UIKit

public extension UICollectionView {
    
    // MARK: - Cell register and reuse
    
    /// Register cell nib
    func yx_registerCellNib<T: UICollectionViewCell>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        let nib = UINib(nibName: name, bundle: nil)
        self.register(nib, forCellWithReuseIdentifier: name)
    }
    
    /// Register cell class
    func yx_registerCellClass<T: UICollectionViewCell>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        self.register(aClass, forCellWithReuseIdentifier: name)
    }
    
    /// Reusable Cell
    func yx_dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
        let name = T.yx_reuseIdentifier
        guard let cell = dequeueReusableCell(withReuseIdentifier: name, for: indexPath) as? T else {
            fatalError("\(name) is not registed")
        }
        return cell
    }
    
    // MARK: - SupplementaryView register and reuse
    
    /// Register supplementaryView nib
    func yx_registerSupplementaryViewNib<T: UICollectionReusableView>(_ aClass: T.Type, of kind: String) {
        let name = aClass.yx_reuseIdentifier
        let nib = UINib(nibName: name, bundle: nil)
        self.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: name)
    }
    
    /// Register supplementaryView class
    func yx_registerSupplementaryViewClass<T: UICollectionReusableView>(_ aClass: T.Type, of kind: String) {
        let name = aClass.yx_reuseIdentifier
        self.register(aClass, forSupplementaryViewOfKind: kind, withReuseIdentifier: name)
    }
    
    /// Reusable supplementaryView
    func yx_dequeueReusableSupplementaryView<T: UICollectionReusableView>(of kind: String, for indexPath: IndexPath) -> T {
        let name = T.yx_reuseIdentifier
        guard let cell = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: name, for: indexPath) as? T else {
            fatalError("\(name) is not registed")
        }
        return cell
    }
}
